import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit'
import { Permission, Role, User } from '@/types/permission'
import permissionService from '@/services/permission'

/**
 * 权限状态接口定义
 */
interface PermissionState {
  // 权限相关
  permissions: Permission[]
  permissionTree: Permission[]
  permissionLoading: boolean
  
  // 角色相关
  roles: Role[]
  roleLoading: boolean
  
  // 用户相关
  users: User[]
  userLoading: boolean
  
  // 当前用户权限
  userPermissions: string[]
  
  // 错误信息
  error: string | null
}

/**
 * 初始状态定义
 * 完全依赖后台数据，不使用模拟数据
 */
const initialState: PermissionState = {
  permissions: [],
  permissionTree: [],
  permissionLoading: false,
  roles: [],
  roleLoading: false,
  users: [],
  userLoading: false,
  userPermissions: [],
  error: null
}

// ============ 异步thunk actions ============

/**
 * 获取权限列表
 */
export const fetchPermissions = createAsyncThunk(
  'permission/fetchPermissions',
  async (params: any = {}, { rejectWithValue }) => {
    try {
      const response = await permissionService.getPermissionList(params)
      if (response.code === 200) {
        return response.data
      } else {
        return rejectWithValue(response.message)
      }
    } catch (error: any) {
      return rejectWithValue(error.message || '获取权限列表失败')
    }
  }
)

/**
 * 获取权限树
 */
export const fetchPermissionTree = createAsyncThunk(
  'permission/fetchPermissionTree',
  async (_, { rejectWithValue }) => {
    try {
      const response = await permissionService.getPermissionTree()
      if (response.code === 200) {
        return response.data
      } else {
        return rejectWithValue(response.message)
      }
    } catch (error: any) {
      return rejectWithValue(error.message || '获取权限树失败')
    }
  }
)

/**
 * 获取角色列表
 */
export const fetchRoles = createAsyncThunk(
  'permission/fetchRoles',
  async (params: any = {}, { rejectWithValue }) => {
    try {
      const response = await permissionService.getRoleList(params)
      if (response.code === 200) {
        return response.data
      } else {
        return rejectWithValue(response.message)
      }
    } catch (error: any) {
      return rejectWithValue(error.message || '获取角色列表失败')
    }
  }
)

/**
 * 获取当前用户权限
 */
export const fetchCurrentUserPermissions = createAsyncThunk(
  'permission/fetchCurrentUserPermissions',
  async (_, { rejectWithValue }) => {
    try {
      const response = await permissionService.getCurrentUserPermissions()
      if (response.code === 200) {
        return response.data
      } else {
        return rejectWithValue(response.message)
      }
    } catch (error: any) {
      return rejectWithValue(error.message || '获取用户权限失败')
    }
  }
)

/**
 * 添加角色
 */
export const addRole = createAsyncThunk(
  'permission/addRole',
  async (roleData: Omit<Role, 'id' | 'createdAt' | 'updatedAt'>, { rejectWithValue }) => {
    try {
      const response = await permissionService.createRole(roleData)
      if (response.code === 200) {
        return response.data
      } else {
        return rejectWithValue(response.message)
      }
    } catch (error: any) {
      return rejectWithValue(error.message || '添加角色失败')
    }
  }
)

/**
 * 更新角色
 */
export const updateRole = createAsyncThunk(
  'permission/updateRole',
  async ({ id, data }: { id: string; data: Partial<Role> }, { rejectWithValue }) => {
    try {
      const response = await permissionService.updateRole(id, data)
      if (response.code === 200) {
        return response.data
      } else {
        return rejectWithValue(response.message)
      }
    } catch (error: any) {
      return rejectWithValue(error.message || '更新角色失败')
    }
  }
)

/**
 * 删除角色
 */
export const deleteRole = createAsyncThunk(
  'permission/deleteRole',
  async (id: string, { rejectWithValue }) => {
    try {
      const response = await permissionService.deleteRole(id)
      if (response.code === 200) {
        return id // 返回删除的角色ID
      } else {
        return rejectWithValue(response.message)
      }
    } catch (error: any) {
      return rejectWithValue(error.message || '删除角色失败')
    }
  }
)

/**
 * 权限状态管理的Redux slice
 */
const permissionSlice = createSlice({
  name: 'permission',
  initialState,
  reducers: {
    /**
     * 清除错误信息
     */
    clearError: (state) => {
      state.error = null
    },
    
    /**
     * 设置用户权限
     */
    setUserPermissions: (state, action: PayloadAction<string[]>) => {
      state.userPermissions = action.payload
    },
    
    /**
     * 重置权限状态
     */
    resetPermissionState: (state) => {
      state.permissions = []
      state.permissionTree = []
      state.roles = []
      state.users = []
      state.userPermissions = []
      state.error = null
    }
  },
  extraReducers: (builder) => {
    // 获取权限列表
    builder
      .addCase(fetchPermissions.pending, (state) => {
        state.permissionLoading = true
        state.error = null
      })
      .addCase(fetchPermissions.fulfilled, (state, action) => {
        state.permissionLoading = false
        state.permissions = action.payload.items || action.payload
        state.error = null
      })
      .addCase(fetchPermissions.rejected, (state, action) => {
        state.permissionLoading = false
        state.error = action.payload as string
      })
    
    // 获取权限树
    builder
      .addCase(fetchPermissionTree.pending, (state) => {
        state.permissionLoading = true
        state.error = null
      })
      .addCase(fetchPermissionTree.fulfilled, (state, action) => {
        state.permissionLoading = false
        state.permissionTree = action.payload
        state.error = null
      })
      .addCase(fetchPermissionTree.rejected, (state, action) => {
        state.permissionLoading = false
        state.error = action.payload as string
      })
    
    // 获取角色列表
    builder
      .addCase(fetchRoles.pending, (state) => {
        state.roleLoading = true
        state.error = null
      })
      .addCase(fetchRoles.fulfilled, (state, action) => {
        state.roleLoading = false
        state.roles = action.payload.items || action.payload
        state.error = null
      })
      .addCase(fetchRoles.rejected, (state, action) => {
        state.roleLoading = false
        state.error = action.payload as string
      })
    
    // 获取当前用户权限
    builder
      .addCase(fetchCurrentUserPermissions.pending, (state) => {
        state.error = null
      })
      .addCase(fetchCurrentUserPermissions.fulfilled, (state, action) => {
        state.userPermissions = action.payload
        state.error = null
      })
      .addCase(fetchCurrentUserPermissions.rejected, (state, action) => {
        state.error = action.payload as string
      })
  }
})

// ============ 导出actions ============

export const {
  clearError,
  setUserPermissions,
  resetPermissionState
} = permissionSlice.actions

/**
 * 导出reducer
 */
export default permissionSlice.reducer

// ============ 导出selectors ============

/** 获取权限列表 */
export const selectPermissions = (state: { permission: PermissionState }) => state.permission.permissions

/** 获取权限树 */
export const selectPermissionTree = (state: { permission: PermissionState }) => state.permission.permissionTree

/** 获取权限加载状态 */
export const selectPermissionLoading = (state: { permission: PermissionState }) => state.permission.permissionLoading

/** 获取角色列表 */
export const selectRoles = (state: { permission: PermissionState }) => state.permission.roles

/** 获取角色加载状态 */
export const selectRoleLoading = (state: { permission: PermissionState }) => state.permission.roleLoading

/** 获取用户列表 */
export const selectUsers = (state: { permission: PermissionState }) => state.permission.users

/** 获取用户加载状态 */
export const selectUserLoading = (state: { permission: PermissionState }) => state.permission.userLoading

/** 获取当前用户权限 */
export const selectUserPermissions = (state: { permission: PermissionState }) => state.permission.userPermissions

/** 获取错误信息 */
export const selectPermissionError = (state: { permission: PermissionState }) => state.permission.error